//
//  ViewController.m
//  HealthyRun
//
//  Created by wubin on 2017/11/22.
//  Copyright © 2017年 clkeji. All rights reserved.
//
#import "WDZAFNetworking.h"
#import "ViewController.h"
#import <HealthKit/HealthKit.h>
@interface ViewController ()
@property (nonatomic, strong) HKHealthStore *healthStore;
@end

@implementation ViewController
- (HKHealthStore *)healthStore{
    if (!_healthStore) {
        _healthStore = [HKHealthStore new];
    }
    return _healthStore;
}
- (IBAction)importData:(UIButton *)sender {
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://192.168.101.101:8080/step.data"]];
    if (data) {
        [self.healthStore saveObjects:[NSKeyedUnarchiver unarchiveObjectWithData:data] withCompletion:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                [SVProgressHUD showSuccessWithStatus:@"success"];
            } else {
                [SVProgressHUD showErrorWithStatus:error.description];
            }
        }];
        
    }
//    [WDZAFNetworking get:@"http://192.168.101.101:8080/step.data" parameters:nil success:^(id  _Nonnull json) {
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [SVProgressHUD showErrorWithStatus:error];
//    } loadingMsg:@"正在下载" errorMsg:@"网络错误"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if ([HKHealthStore isHealthDataAvailable]) {
        NSSet *writeDataTypes = [self dataTypesToWrite];
        NSSet *readDataTypes = [self dataTypesToRead];
        
        [self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {
            if (!success) {
                NSLog(@"You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: %@. If you're using a simulator, try it on a device.", error);
                
                return;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                // Update the user interface based on the current user's health information.
//                [self updateStepCount];
//                [self.healthStore saveObjects:[NSKeyedUnarchiver unarchiveObjectWithFile:[[NSBundle mainBundle] pathForResource:@"step.data" ofType:nil] ] withCompletion:^(BOOL success, NSError * _Nullable error) {
                
//                }];
            });
        }];
    }
}

// Returns the types of data that Fit wishes to write to HealthKit.
- (NSSet *)dataTypesToWrite {
    HKQuantityType *dietaryCalorieStepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    
    return [NSSet setWithObjects:dietaryCalorieStepType, nil];
}

// Returns the types of data that Fit wishes to read from HealthKit.
- (NSSet *)dataTypesToRead {
    HKQuantityType *dietaryCalorieStepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    
    return [NSSet setWithObjects:dietaryCalorieStepType, nil];
}
- (void)updateStepCount{
    //查询采样信息
    HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    //NSSortDescriptor来告诉healthStore怎么样将结果排序
    NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
    NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    //获取当前时间
    NSDate *now = [NSDate date];
    NSCalendar *calender = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponent = [calender components:unitFlags fromDate:now];
    int hour = (int)[dateComponent hour];
    int minute = (int)[dateComponent minute];
    int second = (int)[dateComponent second];
    NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second) * 700 ];
    //时间结果与想象中不同是因为它显示的是0区
    NSLog(@"今天%@",nowDay);
    NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second)  + 86400];
    NSLog(@"明天%@",nextDay);
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nowDay endDate:nextDay options:(HKQueryOptionNone)];
    
    /*查询的基类是HKQuery，这是一个抽象类，能够实现每一种查询目标，这里我们需要查询的步数是一个HKSample类所以对应的查询类是HKSampleQuery。下面的limit参数传1表示查询最近一条数据，查询多条数据只要设置limit的参数值就可以了*/
    
    HKSampleQuery *sampleQuery = [[HKSampleQuery alloc]initWithSampleType:sampleType predicate:predicate limit:0 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable result, NSError * _Nullable error) {
        //设置一个int型变量来作为步数统计
        [NSKeyedArchiver archiveRootObject:result toFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"step.data"]];
        
        UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:@[[NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"step.data"]]] applicationActivities:nil];
        [self presentViewController:controller animated:YES completion:nil];
//        NSData *data = [NSData dataWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"step.data"]];
//        [WDZAFNetworking post:@"http://192.168.101.101:8080/upload" files:@[data] parameters:nil success:^(id  _Nonnull json) {
//            
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            WLog(@"%@",error);
//        } loadingMsg:@"正在发送" errorMsg:@"错误"];
//        NSArray *results = [NSKeyedUnarchiver unarchiveObjectWithFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"step.data"]];
//        int allStepCount = 0;
//        for (int i = 0; i < results.count; i ++) {
//            //把结果转换为字符串类型
//            HKQuantitySample *result = results[i];
//            HKQuantity *quantity = result.quantity;
//            NSMutableString *stepCount = (NSMutableString *)quantity;
//            NSString *stepStr =[ NSString stringWithFormat:@"%@",stepCount];
//            //获取51 count此类字符串前面的数字
//            NSString *str = [stepStr componentsSeparatedByString:@" "][0];
//            int stepNum = [str intValue];
//            NSLog(@"%d",stepNum);
//            //把一天中所有时间段中的步数加到一起
//            allStepCount = allStepCount + stepNum;
//        }
        
        //查询要放在多线程中进行，如果要对UI进行刷新，要回到主线程
//        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
//            self.StepsLable.text = [NSString stringWithFormat:@"%d",allStepCount];
//        }];
    }];
    //执行查询
    [self.healthStore executeQuery:sampleQuery];
}
- (void)addstepWithStepNum:(double)stepNum {
    // Create a new food correlation for the given food item.
    HKQuantitySample *stepCorrelationItem = [self stepCorrelationWithStepNum:stepNum];
    [self.healthStore saveObject:stepCorrelationItem withCompletion:^(BOOL success, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                [self.view endEditing:YES];
                UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [doneAlertView show];
            }
            else {
                NSLog(@"The error was: %@.", error);
                UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [doneAlertView show];
                return ;
            }
        });
    }];
}
- (HKQuantitySample *)stepCorrelationWithStepNum:(double)stepNum {
    NSDate *endDate = [NSDate date];
    NSDate *startDate = [NSDate dateWithTimeInterval:-300 sinceDate:endDate];
    
    HKQuantity *stepQuantityConsumed = [HKQuantity quantityWithUnit:[HKUnit countUnit] doubleValue:stepNum];
    
    HKQuantityType *stepConsumedType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    
    HKDevice *device = [[HKDevice alloc] initWithName:@"iPhone" manufacturer:@"Apple" model:@"iPhone" hardwareVersion:@"iPhone6s plus" firmwareVersion:@"iPhone6s plus" softwareVersion:@"9.3.1" localIdentifier:@"aaron" UDIDeviceIdentifier:@"aaron"];
    //    NSDictionary *stepCorrelationMetadata = @{HKMetadataKeyUDIDeviceIdentifier: @"aaron's test equipment",
    //                                                  HKMetadataKeyDeviceName:@"iPhone",
    //                                                  HKMetadataKeyWorkoutBrandName:@"Apple",
    //                                                  HKMetadataKeyDeviceManufacturerName:@"Apple"};
    HKQuantitySample *stepConsumedSample = [HKQuantitySample quantitySampleWithType:stepConsumedType quantity:stepQuantityConsumed startDate:startDate endDate:endDate device:device metadata:nil];
    return stepConsumedSample;
}


@end
